# Create your views here.

from rest_framework.viewsets import GenericViewSet
from utils.common_mixin import APIListModelMixin
from utils.common_response import APIResponse
from .models import Banner
from home.serializer import Bannerserializer
from django.conf import settings

class BannerView(GenericViewSet, APIListModelMixin):
    queryset = Banner.objects.all().filter(is_delete=False, is_show=True).order_by('orders')[0:settings.BANNER_COUNT]
    serializer_class = Bannerserializer
    cache_key = 'banner_list'



from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet
from .tasks import seckill
from celery.result import AsyncResult
from celery1 import app

class SeckillView(ViewSet):
    @action(methods=['POST'], detail=False)
    def seckill(self, request, *args, **kwargs):
        course_id = request.data.get('course_id')
        task_id = seckill.delay(course_id)
        return APIResponse(msg='您正在排队', task_id=str(task_id))

    @action(methods=['GET'], detail=False)
    def get_result(self, request, *args, **kwargs):
        task_id = request.query_params.get('task_id')
        a = AsyncResult(id=task_id, app=app)
        if a.successful():
            result = a.get()  # True 和 False
            if result:
                return APIResponse(success='1', msg='秒杀成功')
            else:
                return APIResponse(success='0', msg='秒杀失败')
        elif a.status == 'PENDING':
            print('任务等待中被执行')
            return APIResponse(success='2', msg='任务等待中被执行')
        else:
            return APIResponse(success='3', msg='秒杀任务正在执行')
